<?php
namespace app\jobs;

use app\config\Constants;
use app\models\GoodsOrder;
use app\modules\pay\provider\PayFactory;
use app\modules\pay\services\MerchantService;

/**
 * 取消订单的退款任务
 * Class AutoAcceptJob
 * @package app\jobs
 */
class RefundJob {

    private static $handle_type = [Constants::ORDER_CANCEL];

    public function execute($queue,$job){
        if($job['msg_type'] != Constants::MSG_TYPE_ORDER){
            return true;
        }
        if(!in_array($job['event_type'],self::$handle_type)){
            return true;
        }

        $order = GoodsOrder::findOne(['order_no'=>$job['data']['order_no']]);
        if(!$order){
            return false;
        }
        //货到付款
        if($order->pay_method == Constants::PAY_DELIVERY){
            return true;
        }
        //已付款
        if($order->pay_status != Constants::PAY_STATUS_SUCCESS){
            return true;
        }
        //支付记录
        $log = $order->paymentLog;
        if(!$log){
            return false;
        }
        //已付款
        if($log->pay_status != Constants::PAY_STATUS_SUCCESS){
            return true;
        }
        $platform_refund_no = date("YmdHis") . rand(1000,9999);
        $log->setAttribute("platform_refund_no",$platform_refund_no);
        $log->update();

        //发起退款
        $result = PayFactory::getRefundCode($log->platform_order_no,$platform_refund_no,$order->real_price,$order->pay_method,MerchantService::getPaymentById($order->merchant_id)->getConfig());
        if($result['code'] != "000000"){
            return false;
        }
        return true;
    }
}